<template>
  <el-form
    ref="formRef"
    v-loading="loading"
    :model="formData"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    status-icon
    style="height: 250px"
  >
    <!-- 数据部分 -->
    <el-row :gutter="20" justify="center">
      <el-col :span="18" :offset="3" align="center" style="padding-bottom: 15px; margin-top: -20px">
        <el-text type="warning"> 提示: 使用身份证识别器录入劳资专管员信息,点击下载</el-text>
        <el-link
          type="warning"
          :href="downloadUrl"
          style="margin-top: -2px; margin-left: 5px"
          download="CardReaderSetup.exe"
          >身份证识别器</el-link
        >
      </el-col>
      <el-col :span="8">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" disabled placeholder="自动识别身份证" />
        </el-form-item>
      </el-col>
      <el-col :span="2" :offset="0">
        <el-button type="success" :loading="resolveLoading" @click="resolveCard">读身份证</el-button>
      </el-col>
      <el-col :span="8">
        <el-form-item label="身份证号码" prop="cardno">
          <el-input v-model="formData.cardno" disabled placeholder="自动识别身份证" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20" justify="center">
      <el-col :span="8">
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <el-button type="success" :disabled="disCode" @click="tryCode">{{ codeBtn }} </el-button>
      </el-col>
      <el-col :span="8">
        <el-form-item label="验证码" prop="verificationCode">
          <el-input v-model="formData.verificationCode" placeholder="请输入验证码" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20" justify="center">
      <el-col :span="8">
        <el-form-item label="登录密码" prop="password">
          <PasswordInput ref="passwordInputRef" @input-change="handlePasswordChange" />
          <!-- <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" /> -->
        </el-form-item>
      </el-col>
      <el-col :span="2"> </el-col>
      <el-col :span="8">
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            :show-password="true"
            type="password"
            placeholder="请输入确认密码"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-col :span="24" style="display: flex; align-item: center; justify-content: center"> </el-col>
    <modelPromise v-if="dialogModel.visible" :dialog-model="dialogModel" @send-model-close="sendModelClose">
    </modelPromise>
  </el-form>
</template>

<script lang="ts" setup>
import PasswordInput from "@/components/PasswordInput/index.vue";
import { projectADReg, getVerificationCode } from "@/api/account/project/index";
import modelPromise from "@/views/corp/person/common/modelPromise.vue";
import { reactive, ref } from "vue";
import type { FormRules } from "element-plus";
import { ProjectRegType } from "@/api/account/project/types";
import { useRouter } from "vue-router";
import { CardDeviceSocketPromise } from "@/utils/cardDevice";

const downloadUrl = ref("/app/download/SmzTestCardReader_Setup.exe");
const emit = defineEmits(["currentProject", "currentCorp"]);
const router = useRouter();
const loading = ref(false);
const codeBtn = ref("获取验证码");
// const codeCount = ref(3);
const codeCount = ref(60);
const disCode = ref(false);
let codeInterval = ref();
const resolveLoading = ref(false);

const formData = reactive<ProjectRegType>({});
const formRef = ref(ElForm); // 表单/清空重置使用

const dialogModel = reactive({
  visible: false,
  detail: "corp",
  code: "",
});
//枚举

const rules = reactive<FormRules<ProjectRegType>>({
  name: [{ required: true, message: "管理员姓名不能为空", trigger: "blur" }],
  mobile: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  cardno: [
    { required: true, message: "身份证号码不能为空", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号码",
      trigger: "blur",
    },
  ],
  confirmPassword: [{ required: true, trigger: "blur", validator: passwordBlur }],
  password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
  verificationCode: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});
const allowPassword = ref(false);
const handlePasswordChange = (value: any, allow: boolean) => {
  formData.password = value;
  allowPassword.value = allow;
};

//返回上一页
const goBack = () => {
  router.go(-1);
};
const getCode = useThrottleFn(async () => {
  btnToDis();
  let code = await getVerificationCode(formData.mobile ?? "");
  if (code.success) {
    ElMessage.success("验证码发送成功!");
  } else {
    ElMessage.error(code.msg);
    disCode.value = false;
    codeCount.value = 60;
    codeBtn.value = "获取验证码";
    clearInterval(codeInterval.value);
  }
}, 3000);

function btnToDis() {
  disCode.value = true;
  codeInterval.value = setInterval(() => {
    if (codeCount.value > 0) {
      codeCount.value--;
      codeBtn.value = `重新获取 (${codeCount.value})`;
    } else {
      disCode.value = false;
      codeCount.value = 60;
      codeBtn.value = "获取验证码";
      clearInterval(codeInterval.value);
    }
  }, 1000);
}

function tryCode() {
  if (!formData.mobile) {
    ElMessage.warning("请输入手机号码");
    return;
  }
  let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!reg.test(formData.mobile)) {
    return;
  }
  getCode();
}

function clearUp() {
  ElMessage.success("清空成功");
  formRef.value.resetFields();
  formRef.value.clearValidate();
}

async function validation() {
  if (!allowPassword.value) {
    return false;
  }
  return await formRef.value.validate();
}

function passwordBlur(rule: any, value: any, callback: any) {
  if (value === undefined || value === "") {
    callback(new Error("确认密码不能为空"));
  } else {
    if (value != formData.password) {
      callback(new Error("两次密码不一致"));
    } else {
      callback();
    }
  }
}

/* 读取身份证 */
function resolveCard() {
  emit("currentCorp", function (data: any) {
    if (data) {
      dialogModel.code = data.lumpContractorCorpCode;
      resolveLoading.value = true;
      CardDeviceSocketPromise()
        .then((data: any) => {
          console.log(data);
          cardInfo.value = data;
          formData.cardno = data.id;
          formData.name = data.name;
          formData.token = data.token;
          console.log(data);
        })
        .finally(() => {
          resolveLoading.value = false;
        });
    }
  });
}

const cardInfo = ref();
function sendModelClose() {
  dialogModel.visible = false;
}
async function getCardInfo(e: any) {
  let result = JSON.parse(e.data);
  let { success, msg, data } = result;
  if (!success) {
    if (msg == "版本不一致") {
      // if (msg) {
      let box = await ElMessageBox({
        title: "程序下载",
        showCancelButton: true,
        showConfirmButton: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        message: () =>
          h(
            "div",
            {
              style: {},
            },
            [
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                `当前身份证阅读器守护程序版本已过期，请关闭现有程序并点击下面链接重新下载。`
              ),
              h("br", undefined, undefined),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                "程序下载地址"
              ),
              h(
                "a",
                {
                  href: "/app/download/SmzTestCardReader_Setup.exe",
                  target: "_blank",
                  download: "CardReaderSetup.exe",
                  style: {
                    color: "blue",
                    textDecoration: "underline",
                  },
                },
                "点击下载"
              ),
              h("br", undefined, undefined),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                "有关读卡器守护程序使用教程请"
              ),
              h(
                "a",
                {
                  href: "/app/tutorial.html",
                  target: "_blank",
                  style: {
                    color: "blue",
                    textDecoration: "underline",
                  },
                },
                "点击查看"
              ),
            ]
          ),
      })
        .then((val) => true)
        .catch((val) => false);
    } else if (msg == "身份证读卡器信息未登记") {
      dialogModel.visible = true;
    } else {
      ElMessage.error(msg);
    }
    resolveLoading.value = false;
    return;
  }

  cardInfo.value = data;
  formData.cardno = data.id;
  formData.name = data.name;
  formData.token = data.token;
  resolveLoading.value = false;
}

defineExpose({
  clearUp,
  validation,
  formData,
});
</script>
<style lang="scss" scoped>
.div_form {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.div_row {
  position: absolute;
  left: 0;
  right: 0;
  // top: 0;
  // bottom: 0;
  // margin: auto;
}

.card {
  width: 50%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  background-color: #337ecc;
  align-items: center;
  padding: 10px;
}

:deep() .el-card__header {
  padding: 0px;
}

.demo-ruleForm {
  width: 100%;
  padding-top: 20px;
  position: relative;
}

.div-felx {
  display: flex;
  justify-content: center;
}

.input300 {
  width: 300px !important;
}

.el-select .el-input__inner {
  width: 255px !important;
}

.date-picker {
  width: 302px !important;
}

.el-input__wrapper {
  width: 302px !important;
}

// .el-cascader {
//   width: 722px !important;
// }
.custom-cascader {
  width: 302px !important;
}
</style>
